package com.maserb.monitor.database;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.nio.ByteBuffer;
import java.sql.*;
import java.text.SimpleDateFormat;

public class PreparedStatementUtils {

    public static void setInt(PreparedStatement ps, Integer index, Integer val) throws SQLException {
        if (val == null) {
            ps.setNull(index, Types.INTEGER);
        } else {
            ps.setInt(index, val);
        }
    }

    public static void setFloat(PreparedStatement ps, Integer index, Float val) throws SQLException {
        if (val == null) {
            ps.setNull(index, Types.FLOAT);
        } else {
            ps.setDouble(index, val);
        }
    }

    public static void setDouble(PreparedStatement ps, Integer index, Double val) throws SQLException {
        if (val == null) {
            ps.setNull(index, Types.DOUBLE);
        } else {
            ps.setDouble(index, val);
        }
    }

    public static void setString(PreparedStatement ps, Integer index, String val) throws SQLException {
        ps.setString(index, val);
    }

    public static void setDate(PreparedStatement ps, int index, Date val) throws SQLException {
        if (val == null) {
            ps.setNull(index, Types.DATE);
        } else {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            ps.setString(index, sdf.format(val));
        }
    }

    public static void setFloats(PreparedStatement ps, int index, float[] val) throws Exception {
        float fArr[] = val;
        ByteArrayOutputStream bas = new ByteArrayOutputStream();
        DataOutputStream ds = new DataOutputStream(bas);
        for (float f : fArr)
            ds.writeFloat(f);
        byte[] bytes = bas.toByteArray();

        ps.setBytes(index, bytes);
    }

    public static float[] getFloats(ResultSet rs, int index) throws Exception {
        byte[] buffer = rs.getBytes(index);
        ByteArrayInputStream bas = new ByteArrayInputStream(buffer);
        DataInputStream ds = new DataInputStream(bas);
        float[] fArr = new float[buffer.length / 4];  // 4 bytes per float
        for (int i = 0; i < fArr.length; i++) {
            fArr[i] = ds.readFloat();
        }

        return fArr;
    }
}
